// miniprogram/pages/admin/choose/choose.js
const app = getApp();
const uploader = require('../../utils/upload.js');
const util = require('../../utils/util');
var imageUrls = []
Page({

  /**
   * 页面的初始数据
   */
  data: {

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    app.login(user => {
      if (!user.studioid) {
        wx.navigateBack();
        return;
      }
      this.setData({
        user: user,
        _id: options._id
      })
      this.loadOrder(user, options._id);
    });
  },

  loadOrder: function (user, id) {
    imageUrls = []
    wx.cloud.callFunction({
      name: 'crud',
      data: {
        op: 'get',
        table: 'order',
        where: {
          _id: id,
          studioid: user.studioid
        },
        field: {
          customer: true,
          service: true,
          status: true,
          logs: true
        }
      },
      success: res => {
        this.setData({
          order: res.result.data[0]
        });
      }
    });
    wx.cloud.callFunction({
      name: 'crud',
      data: {
        op: 'get',
        table: 'picture',
        where: {
          _id: id,
          studioid: user.studioid
        }
      },
      success: res => {
        let picture = {
          _id: id,
          validity: 30,
          files: []
        };
        if (res.result.data.length > 0) {
          picture = res.result.data[0];
          for (var i = 0; i < picture.files.length; i++) {
            imageUrls.push(picture.files[i].src);
          }
        }
        this.setData({
          picture,
          validity: picture.validity ? picture.validity : 30
        });
      }
    })
  },

  setValidity(e) {
    this.setData({
      validity: e.detail.value
    });
  },

  previewImages(e) {
    // let files = [e.currentTarget.dataset.url];
    // this.data.picture.files.map((v,i)=>{
    //   files.push(v.orgSrc);
    // })
    // let files = [];
    // let index = e.currentTarget.dataset.index;
    // for(var i = index;i<this.data.picture.files.length;i++){
    //   files.push(this.data.picture.files[i].orgSrc);
    // }
    wx.previewImage({
      urls: imageUrls,
      current: e.currentTarget.dataset.url
    })
  },

  // uploadImage_cos: function (node) {
  //   return new Promise((resolve, reject) => {
  //     // let fn = node.src.match(/[^/]+?$/)[0];
  //     let options = {
  //       bucket: 'p-1301301505', // TODO 需要替换为当前用户对应的存储桶
  //       cloudPath: `${app.globalData.user.studioid}/orders/${this.options._id}/${node.name}`, // TODO 需要替换这当前用户对应的路径
  //       filePath: node.src,
  //       success: res => {
  //         console.log(res);
  //         node.src = res.fileID + '/mini';
  //         node.orgSrc = res.fileID;
  //         // node.uploaded = true;
  //         resolve(node)
  //       },
  //       // progress: p=>{
  //       //   wx.set
  //       // },
  //       fail: err => {
  //         reject(err)
  //       }
  //     }
  //     uploader.uploadFile(options);
  //   })
  // },
  uploadImage: function (node) {
    let that = this
    return new Promise((resolve, reject) => {
      wx.showLoading({
        title: '正在上传...',
        icon: 'none'
      });

      wx.cloud.uploadFile({
      
        cloudPath: `studioAsset/${app.globalData.user.studioid}/orders/${this.options._id}/${node.name}`,
        filePath: node.src,
        success(res) {
          console.log('上传', res)
          wx.cloud.getTempFileURL({
            fileList: [res.fileID],
            success(res) {
              console.log('获取http地址', res);
              node.src = res.fileList[0].tempFileURL;
              node.fileID = res.fileList[0].fileID
              // node.orgSrc = res.fileList[0].tempFileURL;     

              resolve(node)

            },
            fail: err => {
              reject(err)
            }
          })

        },
        fail: err => {
          reject(err)
        }
      })

    })
  },
  chooseMessageFile: function () {
    const that = this;
    var files = this.data.picture.files;
    // wx.chooseMessageFile({
    //   type: 'image',
    //   count: 100,
    wx.chooseImage({
      sizeType: ['original'],
      sourceType: ['album'],
      count: 200,
      success: res => {
        wx.showLoading({
          title: '正在上传...',
        })
        //   wx.showNavigationBarLoading();
        console.log(res.tempFiles)
        let selectFiles = [];
        res.tempFiles.map((tempFile, index) => {
          // if (files.find(v=>{return v.name==tempFile.name})) {
          //   wx.showToast({
          //     title: `${tempFile.name}已存在`,
          //     icon: 'none'
          //   })
          //   return;
          // }
          wx.getImageInfo({
            src: tempFile.path,
            success: r => {
              let node = {
                src: tempFile.path,
                orgSrc: tempFile.path,
                time: Date.now().toString(36),
                name: Math.random().toString(36).substr(2) + tempFile.path.match(/\.[^.]+?$/)[0],
                size: tempFile.size,
                width: r.width,
                height: r.height
                // width: r.width / r.height,
                // uploaded: false
              }
              this.uploadImage(node).then(node2 => {
                selectFiles.push(node2);
                files = this.data.picture.files;
                files.push(node2);
                that.setData({
                  'picture.files': files
                });
                if (index == res.tempFiles.length - 1) {
                  // wx.hideNavigationBarLoading();
                  wx.hideLoading()
                  wx.cloud.callFunction({
                    name: 'order',
                    data: {
                      op: 'addImage',
                    //  nodes: selectFiles,
                    nodes:files,
                      id: this.data.order._id,
                      studioid: app.globalData.user.studioid,
                    },
                    success: rr => {
                      console.log(rr);
                    }
                  })
                }
              })
            }
          })
        });
      },
    })
  },

  toggleSort: function (e) {
    let randomSort = !this.data.picture.randomSort;
    this.setData({
      'picture.randomSort': randomSort
    });
    wx.cloud.callFunction({
      name: 'crud',
      data: {
        op: 'update',
        table: 'picture',
        data: {
          _id: this.data.order._id,
          randomSort: randomSort
        }
      },
      success: res => {
        console.log(res.result);
        this.hideModal();
      }
    })
  },


  removeImage(e) {
    const that = this;
    let index = e.currentTarget.dataset.index
    let files = this.data.picture.files;
    let node = files[index];
    console.log(node)
    if (!node.fileID) {
      uploader.deleteFiles({
        bucket: app.globalData.user.studio.bucket,
        files: [node.orgSrc],
        success: r => {
          console.log("Remove images success", r, that.removeImages)
     
        },
        fail: err => {
          console.error("Remove images fail", err, that.removeImages)
        }
      });
    }else{
      wx.cloud.deleteFile({ fileList:[node.fileID], success: res=>{
        console.log('从云存储中删除',res);
    
      }});
    }
    //删除数据库中记录
    wx.cloud.callFunction({
      name: 'order',
      data: {
        op: 'removeImage',
        id: that.data.order._id,
        name: node.name
      },
      success: rr => {
        files.splice(index, 1)
        that.setData({
          'picture.files': files
        })
        console.log(rr);
      }
    })
  },
  setCoupon: function (e) {
    const that = this;
    wx.navigateTo({
      url: '../chooseMorePolicy/chooseMorePolicy',
      events: {
        setCoupon: res => {
          console.log("result", res);
          that.setData({
            ['pr.service.coupon']: res.coupon
          });
        }
      },
      success: res => {
        res.eventChannel.emit('setCoupon', {
          coupon: this.data.pr.service.coupon
        })
      }
    })
  },

  showModal(e) {
    if (this.data.picture.files.length == 0) {
      wx.showToast({
        title: '请选上传图片',
        icon: 'none'
      })
      return;
    }
    let modalname = e.currentTarget.dataset.modalname
    this.setData({
      modalname
    })

  },
  hideModal() {
    this.setData({
      modalname: null
    });
  },

  saveValidity(e) {
    this.setData({
      'picture.validity': this.data.validity
    });
    wx.cloud.callFunction({
      name: 'crud',
      data: {
        op: 'update',
        table: 'picture',
        data: {
          _id: this.data.order._id,
          validity: parseInt(this.data.validity)
        }
      },
      success: res => {
        console.log(res);
        this.hideModal();
      }
    })
  },
  notifyCustomer(e) {
    if (this.data.picture.files.length == 0) {
      wx.showToast({
        title: '请选上传图片',
        icon: 'none'
      })
      return;
    }
    const that = this;
    const order = this.data.order;
    if (!order.logs) {
      order.logs = [];
    }

    order.logs.push({
      time: util.formatTime(new Date()),
      user: app.globalData.user.name,
      text: `${e.currentTarget.dataset.text}`,

    })

    wx.cloud.callFunction({
      name: 'crud',
      data: {
        op: 'update',
        table: 'order',
        data: {
          _id: order._id,
          status: 4,
          logs: order.logs
        }
      },
      success: res => {
        wx.navigateToMiniProgram({
          appId: app.globalData.user.studio.appid,
          envVersion: 'trial',
          path: `/pages/user/choose/index/index?_id=${this.data.order._id}`,
          success: r => {
            wx.navigateBack();
          }
        });

      }
    })
  },
  changeStatus(e) {
    const that = this;
    const order = this.data.order;
    if (!order.logs) {
      order.logs = [];
    }

    order.logs.push({
      time: util.formatTime(new Date()),
      user: app.globalData.user.name,
      text: `${e.currentTarget.dataset.text}`
    })
    wx.cloud.callFunction({
      name: 'crud',
      data: {
        op: 'update',
        table: 'order',
        data: {
          _id: order._id,
          status: parseInt(e.currentTarget.dataset.value),
          logs: order.logs
        }
      },
      success: res => {
        that.setData({
          'order.status': parseInt(e.currentTarget.dataset.value)
        })
      }
    })

  },
  // endChoose(){
  //   wx.cloud.callFunction({
  //     name: 'crud',
  //     data: {
  //       op: 'update',
  //       table: 'order',
  //       data: {_id: this.data.order._id, status: 5}
  //     },
  //     success: res=>{
  //       this.loadOrder(this.data.user,this.data._id)
  //       // wx.navigateToMiniProgram({
  //       //   appId: app.globalData.user.studio.appid,
  //       //   envVersion: 'develop',
  //       //   path: `/pages/user/choose/index/index?_id=${this.data.order._id}`,
  //       //   success: r=>{
  //       //     wx.navigateBack();
  //       //   }
  //       // });        
  //     }
  //   })
  // },

  // 导出选片
  exportChosen: function (e) {
    // TODO 导出选片
    const that = this;
    wx.cloud.callFunction({
      name: 'order',
      data: {
        op: 'export',
        _id: this.options._id,
        title: `${this.data.order.customer.name}-${this.data.order.service.title}-${util.formatTime(new Date()).substr(0, 10)}`
      },
      success: res => {
        console.log(res);
        that.getFileUrl(res.result.fileID);
      }
    })
  },

  //获取云存储文件下载地址，这个地址有效期一天
  getFileUrl(fileID) {
    let that = this;
    wx.cloud.getTempFileURL({
      fileList: [fileID],
      success: res => {
        let url = res.fileList[0].tempFileURL;
        // get temp file URL
        console.log("文件下载链接", url)
        that.setData({
          fileUrl: url
        });
        // if (wx.getSystemInfoSync().platform==='ios')
        // wx.openDocument({
        //   filePath: url
        // });
        wx.downloadFile({
          url: url,
          success: rr => {
            wx.openDocument({
              filePath: rr.tempFilePath
            })
          }
        })

      },
      fail: err => {
        // handle error
      }
    })
  },
  //复制excel文件下载链接
  copyFileUrl() {
    let that = this
    wx.setClipboardData({
      data: that.data.fileUrl,
      success(res) {
        wx.getClipboardData({
          success(res) {
            console.log("复制成功", res.data) // data
          }
        })
      }
    })
  },

  deleteAll: function (e) {
    // TODO 清空原片
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})